package com.xframe.xdal.core.util.redis.pool;

import com.xframe.xdal.config.RedisConfig;
import com.xframe.xdal.core.util.StringUtil;
import lombok.extern.slf4j.Slf4j;
import redis.clients.jedis.JedisPoolConfig;
import redis.clients.jedis.JedisShardInfo;
import redis.clients.jedis.ShardedJedis;
import redis.clients.jedis.ShardedJedisPool;
import redis.clients.jedis.commands.BasicCommands;
import redis.clients.jedis.commands.JedisCommands;
import redis.clients.jedis.commands.MultiKeyCommands;
import redis.clients.jedis.util.Hashing;
import redis.clients.jedis.util.Sharded;

import java.util.ArrayList;
import java.util.List;

/**
 * Created by 敲代码的卡卡罗特
 */
@Slf4j
public class RedisShardedPool implements IRedisPool<ShardedJedis> {


    private ShardedJedisPool pool;//sharded jedis连接池



    @Override
    public void initPool(RedisConfig redisConfig) {
        JedisPoolConfig config = new JedisPoolConfig();

        config.setMaxTotal(redisConfig.getTotal());
        config.setMaxIdle(redisConfig.getMaxIdle());
        config.setMinIdle(redisConfig.getMinIdle());

        config.setTestOnBorrow(redisConfig.isTestBorrow());
        config.setTestOnReturn(redisConfig.isTestReturn());
        //连接耗尽的时候，是否阻塞，false会抛出异常，true阻塞直到超时。默认为true。
        config.setBlockWhenExhausted(true);
        String[] hostsArr = redisConfig.getHosts().split(",");
        List<JedisShardInfo> jedisShardInfoList = new ArrayList<JedisShardInfo>(hostsArr.length);
        for (String hosts : hostsArr) {
            JedisShardInfo jedisShardInfo = new JedisShardInfo(hosts.split(":")[0], Integer.parseInt(hosts.split(":")[1]),
                    1000 * 2);
            if (StringUtil.isNotEmpty(redisConfig.getPassword())) {
                jedisShardInfo.setPassword(redisConfig.getPassword());
            }
            jedisShardInfoList.add(jedisShardInfo);
        }
        pool = new ShardedJedisPool(config, jedisShardInfoList, Hashing.MURMUR_HASH, Sharded.DEFAULT_KEY_TAG_PATTERN);

    }

    @Override
    public JedisCommands getClient() {
        return pool.getResource();
    }

    @Override
    public ShardedJedis getResource() {
        return pool.getResource();
    }

    @Override
    public MultiKeyCommands getMultiKeyCommands() {
        return null;
    }

    @Override
    public BasicCommands getBasicCommands(){
        return null;
    }

    @Override
    public void close(ShardedJedis jedis) {
        try {
            if (jedis != null) {
                jedis.close();
            }
        } catch (Exception e) {
            log.error("return redis resource exception", e);
        }
    }


}
